package com.java.code.itextpdf;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import com.itextpdf.text.pdf.parser.*;
import com.java.code.poi.JavaExcelOper;
import org.junit.Test;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class JavaPdfOper {
    /**
     * pdf平均分页
     */
    @Test
    public void pdfSplitAverage(String path, String source) throws Exception {
        int aerage = 30;

        PdfReader reader = new PdfReader(path + source);
        int pageNum = reader.getNumberOfPages();

        //101 11*9 99 2  1-11 12-
        int startPage = 1;
        int endPage = pageNum;
        int cell = (int) Math.ceil(pageNum / aerage);
        for (int index = 0; index < aerage; index++) {
            if (index == aerage - 1) {
                endPage = pageNum;
            } else {
                endPage = cell + startPage - 1;
            }
            copyPdf(path + source, path + (index + 1) + ".pdf", startPage + "-" + endPage);
            //System.out.println( startPage + "-" + endPage);
            startPage = endPage + 1;
        }
//        System.out.println("copy完成......");
    }

    /**
     * 复制pdf文档
     *
     * @param sourceFile 源文件
     * @param targetFile 目标文件
     * @param ranges     复制规则     "1-7"表示复制1到7页、"8-"表示复制从第八页之后到文档末尾
     */
    public void copyPdf(String sourceFile, String targetFile, String ranges) throws Exception {
        PdfReader pdfReader = new PdfReader(sourceFile);
        PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream(targetFile));
        pdfReader.selectPages(ranges);
        pdfStamper.close();
    }

    /**
     * 多个PDF合并功能
     *
     * @param files    多个PDF的路径
     * @param savePath 生成的新PDF绝对路径
     */
    public void mergePdfFiles(String[] files, String savePath) {
        if (files.length > 0) {
            try {
                Document document = new Document(new PdfReader(files[0]).getPageSize(1));
                PdfCopy copy = new PdfCopy(document, new FileOutputStream(savePath));
                document.open();
                for (String file : files) {
                    PdfReader reader = new PdfReader(file);
                    int n = reader.getNumberOfPages();
                    for (int j = 1; j <= n; j++) {
                        document.newPage();
                        PdfImportedPage page = copy.getImportedPage(reader, j);
                        copy.addPage(page);
                    }
                }
                document.close();
            } catch (IOException | DocumentException e) {
                e.printStackTrace();
            }
        }
    }


}
